﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tracy.DataModel;
using System.IO;
using System.Diagnostics;
using SharedLib;
using Microsoft.Win32;
using System.Collections.Concurrent;
using Tracy.Messages;
using System.Collections.Specialized;
using Tracy.DataModel.DownloadAdapter;
using SharedLib.Helpers;

namespace Tracy.Plugins.DownloadAdapters
{
    public class EmuleAdapter : IDownloadAdapter
    {
        private string _installFolder;
        private string _applicationFullPath;
        private bool _notifyOnNewDownload = true;
        private string _incomingDir = null;
        private string _lastSavedDir = null;
        private CalculateOnce<string> _tempDownloadFolderCalculator;
        private void CheckRegistry(){
            RegistryKey regdir = Registry.CurrentUser.OpenSubKey("SOFTWARE", false);
            regdir = regdir.OpenSubKey("easyMule", false);
            if (regdir != null)
            {
                //Console.WriteLine("easyMule Registry Key found");
                object installPath = regdir.GetValue("InstallPath");
                object fileName = regdir.GetValue("FileName");
                if (installPath != null && fileName != null)
                {
                    _installFolder = installPath.ToString();
                    _applicationFullPath = installPath.ToString() + fileName.ToString();
                    //Console.WriteLine("easyMule exe found: " + rtn);
                    if (!File.Exists(_applicationFullPath)) _applicationFullPath = null;
                }
            }
        }
        public void Init(StringDictionary parameters) { }

        private string PreferencesFileName
        {
            get { return _installFolder + "config\\preferences.ini"; }
        }

        private void ParsePreferences()
        {
            if (File.Exists(PreferencesFileName))
            {
                string line = "";
                StreamReader sr = new StreamReader(PreferencesFileName);
                try
                {
                    while (!sr.EndOfStream)
                    {
                        line = sr.ReadLine();
                        if (line.StartsWith("NewTaskDlg"))
                        {
                            _notifyOnNewDownload = (line.Substring(11) == "1"); 
                        }
                        else if (line.StartsWith("IncomingDir"))
                        {
                            _incomingDir = line.Substring(12);
                            if (!_incomingDir.EndsWith("\\")) _incomingDir += "\\";
                        }
                        else if (line.StartsWith("SaveLocation0"))
                        {
                            _lastSavedDir = line.Substring(14);
                            if (!_lastSavedDir.EndsWith("\\")) _lastSavedDir += "\\";
                        }
                    }
                }
                finally
                {
                    sr.Close();
                }


            }

        }
        public EmuleAdapter()
        {
            CheckRegistry();
            ParsePreferences();

            _tempDownloadFolderCalculator = new CalculateOnce<string>(() =>
            {
                ParsePreferences();
                if (_notifyOnNewDownload && !String.IsNullOrEmpty(_lastSavedDir))
                {
                    return _lastSavedDir;
                }
                return _incomingDir;
            });
        }


        public void Download(Resource resource, string defaultPath)
        {
            if (resource == null) return;
            if (IsResourceTypeSupported(resource.GetResourceType()))
            {
                Process.Start(_applicationFullPath, "\"" + resource.Url + "\"");
            }
        }


        public bool IsAvailable()
        {
            return _applicationFullPath != null;
        }

        public bool IsResourceTypeSupported(string type)
        {
            if (IsAvailable())
            {
                if (type == "Emule") return true;
            }
            return false;
        }

        public string[] GetTempFileExts(string type)
        {
            if (type == "Emule") return new string[]{ ".part"};
            return null;
        }

        public string GetValidFileName(string fileName)
        {
            if(fileName == null)return null;
            return fileName.Replace("?", "-").Replace("\\", "-").Replace("/", "-").Replace("*", "-").Replace("\"", "-").Replace(":", "-").Replace("<", "-").Replace(">", "-");
        }

        

        public string GetTempDownloadFolder(string preferredFolder, MediaFile file)
        {
            _tempDownloadFolderCalculator.Execute();
            return _tempDownloadFolderCalculator.Result;
        }
    }
}
